package com.general.campus.jdbc;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

/**
 * @ClassName MySQLJdbcDataSourceServlet
 * @Desc: mysql 内存数据库的servlet JNDI 实现
 * @Author wangxuan
 * @Date: 2021/6/17 8:47
 * @Verson: 1.0
 **/
public class MySQLJdbcDataSourceServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/MyDB");
            Connection conn = ds.getConnection();
            writer.println("Get mysql connection success!"+conn);

            Statement statement = conn.createStatement();
            String sql = "select language_id, name from language";
            ResultSet rs = statement.executeQuery(sql);

            while (rs.next()) {
                writer.println(String.format("languageId #%s:  %s",
                        rs.getInt("language_id"), rs.getString("name")));

            }
        } catch (NamingException ex) {
            System.err.println(ex);
            writer.write("Get mysql connection NamingException, e ["+ex+"]");
        } catch (SQLException ex) {
            System.err.println(ex);
            writer.write("Get mysql connection SQLException, e ["+ex+"]");
        }
    }
}
